var loginData = {};
var iswechat = isWechat();
var pageNumber = 1;
/* 5秒钟轮询一次，一旦有新的评论，立即中止轮询。*/
var polling = setInterval(function(){
   pollingList();
},5000);


$(document).ready(function() {
  // 微信登录
  if (isWechat() && wxUserInfo.nickname != '') {
    // console.log(isWechat()+wxUserInfo.nickname);
    wxLogin(wxUserInfo, (function(result) {
      loginData.id = result.id;
      loginData.token = result.token;
    }), ifBind);
  }
});

function ifBind() {
  wxRegister(wxUserInfo, (function(result) {
    loginData.id = result.id;
    loginData.token = result.token;
  }), function() {
    console.log('微信注册失败！')
  });
}

/* 展开详情 */
$('.sec-desc-img-mini').on('click',function() {
  $(this).hide();
  $('.sec-desc-img-full').slideDown(300);
  $('.img-download-btn').fadeIn(800).addClass('img-download-btn-show');
});

/* 分享按钮 */
$('.img-share-btn').on('click',function() {
  $('.bg-shandow').fadeIn(200);
  $('section').addClass('filter');
});

/* 隐藏分享提示 */
$('.bg-shandow').on('click',function() {
  $('.bg-shandow').fadeOut(200);
  $('section').removeClass('filter');
});
/* 下载 */
$('.img-download-btn').on('click',function() {
  window.location.href = 'http://a.app.qq.com/o/simple.jsp?pkgname=com.lalocal.lalocal';
});


/* 评论按钮 */
$('.btn-send').on('click',function() {
  if(!iswechat) {
    alertPlus('red','请在微信打开此页面评论哦~');
    return;
  }
  var _text = $('#ipt-comment').val();
  sendComment(loginData, _text, refreshList);
  $('#ipt-comment').val('');
});

/* 点击新评论 */
$('.btn-new-msg').on('click',function() {
  refreshList();
  $(this).slideUp(300);
  polling = setInterval(function(){
     pollingList();
  },5000);

});

/* 查看更多 */
$('.btn-more-comments').on('click',function() {
  if(!iswechat) {
    alertPlus('red','请从微信打开查看更多评论哦~');
    return;
  }
  console.log('>>>>>>'+pageNumber);
  if(pageNumber >= totalPages){
    $(this).html('已经到底啦！').addClass('btn-grey');
    return;
  }
  $(this).html('正在加载中…');
  pageNumber++;
  addList(pageNumber);
});

// 初始化评论
initReply();


/******************
 *
 *   以下为函数部分
 *
 ******************/

/* 初始化评论功能，点击评论弹出回复框 *******************/
function initReply(){
  $('.box-comment').on('click', function() {
    var _parentId = $(this).attr('value');
    var _parentName = $(this).attr('nickname');
    toggleReplyBox($(this), _parentName);
    $('.btn-reply-send').off('click').on('click', function() {
      if(!iswechat) {
        alertPlus('red','请从微信打开此页面回复哦~');
        return;
      }
      var _text = $('#ipt-reply').val();
      sendReply(loginData, _text, _parentId, refreshList);
    })
  })
}

/* 显示或者隐藏回复框 *******************/
function toggleReplyBox($obj, parentName) {
  if($obj.children('.box-reply-input').length==0){
    $('.box-reply-input').remove();
    var replyHtml = '<div class="box-reply-input">' +
      '<input type="text" class="ipt-reply" id="ipt-reply" placeholder="回复' + parentName + '：">' +
      '<button class="btn-reply-send">回复</button>' +
      '</div>';
    $obj.append(replyHtml);
    $('#ipt-reply').attr('placeholder', '回复 ' + parentName + '：');
    $('#ipt-reply')[0].focus();
  } else {
    $obj.children('.box-reply-input').remove();
  }

}


/* 刷新评论列表 *******************/
function refreshList() {
  console.log('refresh');
  $.ajax({
    url: 'ajax/refresh',
    type: 'get',
    async: true,
    data: {
      targetId: targetId,
      targetType: targetType,
      pageNumber:1
    },
    dataType: 'json',
    success: function(data) {
      if (data.message === 'success') {
        // alertPlus('green','刷新成功!');
        totalRows = data.result.totalRows;
        refreshListHTML(data.result.rows);
        initReply();
      }
      else {
        console.log('刷新失败');
      }
    }
  });
}



/* 查询，计算评论总数差 *******************/
function pollingList() {
  $.ajax({
    url: 'ajax/refresh',
    type: 'get',
    async: true,
    data: {
      targetId: targetId,
      targetType: targetType,
      pageNumber:1
    },
    dataType: 'json',
    success: function(data) {
      if (data.message === 'success') {
        if((data.result.totalRows - Number(totalRows))>0){
          totalRows = data.result.totalRows;
          clearInterval(polling);
          $('.btn-new-msg').slideDown(300);
        }
      }
      else {
        console.log('刷新失败');
      }
    }
  });
}

/* 更多评论 *******************/
function addList(pageNumber) {
  $.ajax({
    url: 'ajax/refresh',
    type: 'get',
    async: true,
    data: {
      targetId: targetId,
      targetType: targetType,
      pageNumber:pageNumber
    },
    dataType: 'json',
    success: function(data) {
      if (data.message === 'success') {
        // alertPlus('green','刷新成功!');
        totalRows = data.result.totalRows;
        addListHTML(data.result.rows);
        initReply();
        $('.btn-more-comments').html('查看更多评论');
      }
      else {
        console.log('刷新失败');
      }
    }
  });
}

/* 刷新评论列表*******************/
function refreshListHTML(rows){
  var _list = [];
  for(i in rows) {
    var el = rows[i];
    var ifReplyHTML = '';
    if(el.targetUser!=null){
      ifReplyHTML = '<span class="color-grey"> 回复 </span><span>'+el.targetUser.nickName+'</span>';
    }
    var commentHTML = '<div class="box-comment" value="'+el.id+'" nickname="'+el.user.nickName+'">'
      +'<div class="box-comment-usr">'
        +'<img src="'+el.user.avatar+'" alt="" class="img-comment-avatar">'
        +'<div class="box-comment-nick">'
          +'<p class="p-comment-name">'+el.user.nickName
          +ifReplyHTML
        +'</p>'
          +'<p class="p-comment-time">'+el.dateTime+'</p>'
        +'</div>'
      +'</div>'
      +'<div class="box-comment-main">'
        +'<p class="p-comment-main">'+el.content+'</p>'
      +'</div>'
    +'</div>';
    _list.push(commentHTML);
  }
  $('.comments-list').html(_list.join('\n'));
}



/* 在末尾增加更多评论*******************/
function addListHTML(rows){
  var _list = [];
  for(i in rows) {
    var el = rows[i];
    var ifReplyHTML = '';
    if(el.targetUser!=null){
      ifReplyHTML = '<span class="color-grey"> 回复 </span><span>'+el.targetUser.nickName+'</span>';
    }
    var commentHTML = '<div class="box-comment" value="'+el.id+'" nickname="'+el.user.nickName+'">'
      +'<div class="box-comment-usr">'
        +'<img src="'+el.user.avatar+'" alt="" class="img-comment-avatar">'
        +'<div class="box-comment-nick">'
          +'<p class="p-comment-name">'+el.user.nickName
          +ifReplyHTML
        +'</p>'
          +'<p class="p-comment-time">'+el.dateTime+'</p>'
        +'</div>'
      +'</div>'
      +'<div class="box-comment-main">'
        +'<p class="p-comment-main">'+el.content+'</p>'
      +'</div>'
    +'</div>';
    _list.push(commentHTML);
  }
  $('.comments-list').append(_list.join('\n'));
}


/* 发评论 （头部参数，评论内容，成功回调） *******************/
function sendComment(headers, commentText, successCallback) {
  if (commentText === null || commentText === '') {
    return;
  }

  $.ajax({
    url: 'ajax/sendcomment',
    type: 'post',
    async: true,
    data: {
      userId: headers.id,
      token: headers.token,
      content: commentText,
      targetId: targetId,
      targetType: targetType
    },
    dataType: 'json',
    success: function(data) {
      if (data.message === 'success') {
        alertPlus('green','评论成功!');
        successCallback();

      }
      else {
        alertPlus('red','评论出错啦!请再试一次~');
      }
    }
  });
}

/* 发回复（头部参数，回复内容，被回复的评论id，成功回调）*******************/
function sendReply(headers, commentText, parentId, successCallback) {
  if (commentText === null || commentText === '') {
    return;
  }
  $.ajax({
    url: 'ajax/sendreply',
    type: 'post',
    async: true,
    data: {
      userId: headers.id,
      token: headers.token,
      content: commentText,
      parentId: parentId,
    },
    dataType: 'json',
    success: function(data) {
      if (data.message === 'success') {
        alertPlus('green','回复成功!');
        successCallback();
      }
      else {
        alertPlus('red','评论出错啦!请再试一次~');
      }
    }
  });
}
